/*
** draw.c for draw in /home/gjura_r//SDL/projet
** 
** Made by romain gjura
** Login   <gjura_r@epitech.net>
** 
** Started on  Fri Apr 12 17:02:27 2013 romain gjura
** Last update Thu Apr 18 11:54:35 2013 romain gjura
*/

#include <stdio.h>
#include <stdlib.h>
#include <SDL/SDL.h>
#include "./includes/draw.h"

int		find_value_x(int **tab, int x, int y, 
			     t_ressource *bg, 
			     SDL_Surface *elem)
{
  int		decal = 0;
  int		lim = 0;
  int		i = 0;

  while (lim < x)
    {
      i = 0;
      while (i < OBJ)
	{
	  if (tab[y][lim] == i)
	    decal += bg->r_tab[i]->w;
	  i++;
	}
      lim++;
    }
  return decal;
}

int		find_value_y(int **tab, int x, int y, int line, 
			     t_ressource *bg,
			     SDL_Surface *elem)
{
  int		decal = 0;
  int		lim = line;
  int		i = 0;

  while (lim >= y)
    {
      i = 0;
      while (i < OBJ)
	{
	  if (tab[lim][x] == i)
	    decal += bg->r_tab[i]->h;
	  i++;
	}
      lim--;
    }  
  return decal;
}



void		put_background(t_map *map, t_aff *aff, t_ressource *bg)
{
  int		x = 0, y = (map->nb_line - 1);
  int		val_y = 0;
  int		i = 1;
  int		ref = 0;

  while (x < map->nb_col)
    {
      y = (map->nb_line - 1);
      while (y > 0)
	{
	  i = 1;
	  while (i < OBJ)
	    {
	      if (map->tab[y][x] == i)
		{
		  if (x > 0)
		    bg->pos.x = find_value_x(map->tab, x, y, bg, bg->r_tab[i]);
		  if (y > 0)
		    bg->pos.y -= find_value_y(map->tab, x, y, map->nb_line - 1, 
					      bg, bg->r_tab[i]);
		  if (bg->pos.x < WIDTH)
		    SDL_BlitSurface(bg->r_tab[i], NULL, aff->cam, &bg->pos);
		}
	      i++;	    
	    }
	  y--;
	  bg->pos.x = 0;
	  bg->pos.y = HEIGTH;
	}
      x++;
    }
}

int		init_sdl(t_map *map)
{
  t_ressource	bg;
  t_aff		aff;

  if (SDL_Init(SDL_INIT_VIDEO) == -1)
    {
      fprintf(stderr, "Error: SDL failed: %s\n", SDL_GetError());
      return EXIT_FAILURE;
    }
  if ((aff.cam = SDL_SetVideoMode(WIDTH, HEIGTH, 32, SDL_HWSURFACE | SDL_DOUBLEBUF)) == NULL)
    {
      fprintf(stderr, "Error: SDL failed: %s\n", SDL_GetError());
      return EXIT_FAILURE;
    }
  SDL_FillRect(aff.cam, NULL, SDL_MapRGB(aff.cam->format, 51, 204, 255));
  init_ressource(&bg);
  put_background(map, &aff, &bg);
  SDL_Flip(aff.cam);
  wait_for_event(&aff, map);
  SDL_FreeSurface(aff.cam);
  SDL_Quit();
  return EXIT_SUCCESS;
}
